package cn.glenn.egarticle0519.controller;

import cn.glenn.egarticle0519.base.response.JsonResult;
import cn.glenn.egarticle0519.mapper.UserMapper;
import cn.glenn.egarticle0519.pojo.dto.UserArticleParam;
import cn.glenn.egarticle0519.pojo.dto.UserLoginParam;
import cn.glenn.egarticle0519.pojo.enity.Article;
import cn.glenn.egarticle0519.pojo.vo.ArticleVO;
import cn.glenn.egarticle0519.pojo.vo.UserVO;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/v1/user/")
@Validated
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @Parameters({
            @Parameter(name = "username",description = "用户名"),
            @Parameter(name = "password",description = "密码")
    })
    public JsonResult login(@Valid @RequestBody UserLoginParam param, HttpSession session) {
        UserVO user = userMapper.login(param);
        log.debug("user:{}", user);
        if (user != null) {
            session.setAttribute("user", user);
            return JsonResult.success(user);
        }else return JsonResult.usernamePwdError();
    }

    @PostMapping("article")
    public JsonResult postArticle(HttpSession session,@Valid @RequestBody UserArticleParam param){
        UserVO user = (UserVO) session.getAttribute("user");
        log.debug("param:{}", param);
        Article article = new Article();
        BeanUtils.copyProperties(param, article);
        article.setUserId(user.getId());
        int result = userMapper.insertArticle(article);
        log.debug("result:{}", result);
        return JsonResult.success(result);
    }

    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Valid @Range(min = 1,max = 100,message = "文章编号为1-100") Long id){
        ArticleVO articleVO = userMapper.selectByArticleId(id);
        log.debug("articleVO:{}", articleVO);
        return JsonResult.success(articleVO);
    }

}
